package com.ifnk.portaljava.hlyt.etl;

import com.ifnk.portaljava.hlyt.etl.beans.GnData;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * <p>Title:包含GnData数据的文件类 </p>
 *
 * <p>Description: 有检查文件名是否合法、插入文件中包含的所有数据的方法</p>
 *
 * <p>Copyright: Copyright (c) 2010</p>
 *
 * <p>Company: </p>
 * 
 * @author chengzhang.shi.hlyt@gmail.com
 * @version 1.0
 */
public class GnFile {

	private static Log loger = LogFactory.getLog(GnFile.class);
	private ArrayList<GnData> datas = new ArrayList<GnData>();

	public GnFile() {

	}

	public GnFile(File file) {
		setFile(file);
	}

	public boolean setFile(File file) {
		if (checkFileName(file)) {
			BufferedReader br = null;
			try {
				br = new BufferedReader(new FileReader(file));
				String line = null;
				while ((line = br.readLine()) != null) {
					GnData gnData = new GnData();
					boolean flag = gnData.setData(line);
					if (flag) {
						datas.add(gnData);
					}
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if(br != null) {
					try {
						br.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}

			return true;
		}
		return false;
	}

	public static boolean checkFileName(File file) {
		String fileName = file.getName();
		String[] tmp = fileName.split("\\.");

		if (tmp.length == 2 && "csv".equals(tmp[1])) {
			tmp = tmp[0].split("_");

			if (tmp.length == 2 && "GnKPI".equals(tmp[0])
					&& tmp[1].length() == 14) {
				return true;
			}
		}
		loger.error("文件名不合适！：" + file.getName());
		return false;
	}
	
	public void insert() {
		Iterator<GnData> iterator = datas.iterator();
		while(iterator.hasNext()) {
			iterator.next().insert();
		}
	}

	public ArrayList<GnData> getDatas() {
		return datas;
	}
	
}
